#!/usr/bin/bash
# --2022.01.14
# --linjinting


function checkAndSetVar() {
    # 检查变量
    args=
    if [ ! -n "${auth}" ]; then
      auth="-auth guess"
      echo "Because the auth variable is empty, all use the default value:${auth}"
    fi
    if [ ! -n "${rfbauth}" ]; then
      rfbauth="-rfbauth /etc/x11vnc.pass"
      echo "Because the auth variable is empty, all use the default value:${rfbauth}"
    fi
    #
    if [ ! -n "${rfbport}" ]; then
      rfbport="-rfbport 5900"
      echo "Because the rfbport variable is empty, all use the default value:${rfbport}"
    fi
    #
    if [ ! -n "${display}" ]; then
      display="-display :0"
      echo "Because the display variable is empty, all use the default value:${display}"
    fi
    #
    if [ ! -n "${logfile}" ]; then
        logfile="-o /var/log/x11vnc.log"
        echo "Because the logfile variable is empty, all use the default value:${logfile}"
    fi
    #
    if [ -n "${forever}" ]; then
        args="${args} -forever"
        echo "forever is set"
    fi
    #
    if [ -n "${loop}" ]; then
        args="${args} -loop"
        echo "loop is set"
    fi

    echo -e "\033[34mThe values of the variables are:
    auth=${auth}
    rfbauth=${rfbauth}
    rfbport=${rfbport}
    logfile=${logfile}
    forever=${forever}
    loop=${loop}
    \033[0m"
}


function f_auto_server(){
    if [ -f /bin/systemctl ]; then
        echo "now copy vncserver.service to /etc/systemd/system"
        cp -arf ../vncserver.service /etc/systemd/system/vncserver.service
        echo "now reload systemd service"
        systemctl daemon-reload
        echo "now start server"
        systemctl start vncserver.service
        systemctl status vncserver.service
        echo "now Add to auto start server"
        systemctl enable vncserver.service

    elif [ -f /bin/chkconfig ]; then
        echo "now copy start_vnc.sh to /etc/init.d/vnc"
        cp -arf ./start_vnc.sh /etc/init.d/vnc
        chmod +x /etc/init.d/vnc
        echo "now start server"
        service vnc restart
        echo "now Add to auto start server"
        chkconfig vnc on
    else
        echo "...................."
        exit 0
    fi
}

# 读取变量
source ./vnc.init.config
# 检查设置变量
checkAndSetVar

echo "copy x11vnc to /bin/"
cp -arf ../x11vnc /bin/

echo "now set password for vnc server..."
/bin/x11vnc -storepasswd /etc/x11vnc.pass
chmod 666 /etc/x11vnc.pass

f_auto_server